package com.atguigu.spxz.product.service.impl;

import com.atguigu.spxz.product.mapper.CategoryMapper;
import com.atguigu.spxz.product.service.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    public List<Category> findByParentId(long id) {
        return categoryMapper.findByParentId(id);
    }


    @Cacheable(value = "category",key = "'findCategoryTree'")
    @Override
    public List<Category> findCategoryTree() {

        List<Category> categoryList = categoryMapper.findAll();


//        ArrayList<Category> onecategoryList = new ArrayList<>();
//
//        categoryList.stream().filter(category -> {
//            if (category.getParentId()==0){
//                return true;
//            }
//            return false;
//        }).collect(Collectors.toList());

        List<Category> onecategoryList  = categoryList.stream().filter(category -> category.getParentId()==0).collect(Collectors.toList());

        //遍历一级分类
        onecategoryList.stream().forEach(onecategory -> {

            //筛选一级下面的二级列表
            List<Category> twocategoryList = categoryList.stream().filter(category -> category.getParentId().longValue()==onecategory.getId()).collect(Collectors.toList());



             //遍历二级分类列表
            twocategoryList.forEach(twoCategory -> {
                //筛选每个二级分类的三级分类列表
                List<Category> threeCategoryList = categoryList.stream().filter(category ->category.getParentId().longValue()==twoCategory.getId()).collect(Collectors.toList());
                twoCategory.setChildren(threeCategoryList);
            });
            onecategory.setChildren(twocategoryList);
        });

        return onecategoryList;
    }

}
